import 'package:install_plugin/install_plugin.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../util.dart';
import 'model.dart';
import 'version_update_view/index.dart';

import '../httputils/http_man.dart';
import '../httputils/urlpath.dart';

/// @Author : 崔成

/// @Time : On 2023/10/11 9:02

class CheckUpdate {
  static final CheckUpdate instance = CheckUpdate._interval();
  factory CheckUpdate() => instance;
  CheckUpdate._interval();

  Map<String, dynamic>? json;

  Future<void> checkUpdate() async {
    var res = await HttpMan.instance.get(
      UrlPath.checkUpdate,
      loadding: false,
    );

    if (res.isSuccess) {
      var data = res.data;
      var md = VersionModel.fromJson(data);
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      var currVersion = packageInfo.version;
      var flag = md.versionName.compareTo(currVersion);
      if (flag == 1) {
        await alert(md);
      }
    }
  }

  Future<void> alert(VersionModel md) async {
    await Get.to(
      () => const VersionUpdateViewPage(),
      binding: VersionUpdateViewBinding(),
      arguments: md,
      transition: Transition.fade,
      fullscreenDialog: true,
      opaque: false,
      popGesture: false,
    );
  }

  Future<bool> download(
    String url, {
    void Function(int, int)? onReceiveProgress,
  }) async {
    var savePath = await FileManager().tempPath('version');
    var res = await HttpMan.instance.download(
      url,
      savePath,
      onReceiveProgress: onReceiveProgress,
    );
    if (!res.isSuccess) {
      Hud.toast(res.msg);
    } else {
      await InstallPlugin.installApk(savePath);
    }

    return res.isSuccess;
  }
}
